import React, {Component} from 'react'
import {Button, Card, Form, Input, message, Space, Spin} from 'antd';
import {MinusCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {RelatedLink} from '../../../../types/Frame';
import {modifyRelatedLinksReq, relatedLinkReq} from '../../../../requests/Frame';
import {getRes} from '../../../../configFile';
import {Store} from 'antd/lib/form/interface';


interface IState {
    isLoading: boolean
    initialLinkList: Array<RelatedLink>
}

interface IProps {
}

export default class RelatedLinkModify extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            isLoading: true,
            initialLinkList: []
        }
    }

    //函数引用
    addRef: ((defaultValue?: any, insertIndex?: number | undefined) => void) | undefined;

    async componentDidMount() {
        //获取初始值
        await this.getInit()
        //表单加入初始值
        this.state.initialLinkList.reverse().map(item => {
            if (!!this.addRef)
                this.addRef({link: item.link, linkName: item.linkName}, 0)
            return undefined
        })
        this.setState({
            ...this.state,
            isLoading: false
        })
    }

    //获取初始链接列表
    getInit = async () => {
        try {
            const res = getRes(await relatedLinkReq())
            this.setState({
                ...this.state,
                initialLinkList: res.data
            })
        } catch (err) {
            message.error(err.toString())
        }
    }

    //提交新的相关链接
    sendNewLinks = async (RelatedLink: Array<RelatedLink>) => {
        this.setState({
            ...this.state,
            isLoading: true
        })
        try {
            const res = getRes(await modifyRelatedLinksReq(RelatedLink))
            if (res.isSuccessful === true) //修改成功
                message.success('修改成功')
            else
                message.error('修改失败')
        } catch (err) {
            message.error(JSON.stringify(err))
        } finally {
            this.setState({
                ...this.state,
                isLoading: false
            })
        }
    }

    //表单提交
    onFinish = (values: Store) => {
        values.relatedLinks = values.relatedLinks.map((link: { link: string, linkName: string }) => {
            if (/^http.*/.test(link.link)) {
                return link;
            }
            link.link = 'http://' + link.link;
            return link;
        })
        const valueToUse: Array<RelatedLink> = values.relatedLinks.map((item: Object, index: number) => {
            return Object.assign({}, item, {sequence: index})
        })
        this.sendNewLinks(valueToUse)
    };


    render() {
        return (
            <div>
                <Card title="更改相关链接（添加顺序即为显示顺序）" bordered={false}>
                    <Spin spinning={this.state.isLoading}>
                        <Form name="dynamic_form_nest_item" onFinish={this.onFinish} autoComplete="off">
                            <Form.List name="relatedLinks">
                                {(fields, {add, remove}) => {
                                    //传出函数引用
                                    this.addRef = add
                                    return (
                                        <div>
                                            <Form.Item>
                                                <Button
                                                    type="dashed"
                                                    onClick={() => {
                                                        add(undefined, 0);
                                                    }}
                                                    block
                                                >
                                                    <PlusOutlined/>头部增加相关链接
                                                </Button>
                                            </Form.Item>
                                            {fields.map(field =>
                                                <Space key={field.key}
                                                       style={{display: 'flex', marginBottom: 0, alignItems: 'start'}}>
                                                    <Form.Item
                                                        {...field}
                                                        name={[field.name, 'link']}
                                                        rules={[{required: true, message: '链接不可省略'}]}
                                                    >
                                                        <Input placeholder="链接URL"/>
                                                    </Form.Item>

                                                    <Form.Item
                                                        {...field}
                                                        name={[field.name, 'linkName']}
                                                        rules={[{required: true, message: '链接名称不可省略'}]}
                                                    >
                                                        <Input placeholder="链接名称"/>
                                                    </Form.Item>

                                                    <MinusCircleOutlined
                                                        style={{fontSize: '32px', lineHeight: '100%'}}
                                                        onClick={() => {
                                                            remove(field.name);
                                                        }}
                                                    />
                                                </Space>
                                            )}

                                            <Form.Item>
                                                <Button
                                                    type="dashed"
                                                    onClick={() => {
                                                        add();
                                                    }}
                                                    block
                                                >
                                                    <PlusOutlined/>尾部增加相关链接
                                                </Button>
                                            </Form.Item>
                                        </div>
                                    );
                                }}
                            </Form.List>

                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>
                            </Form.Item>
                        </Form>
                    </Spin>
                </Card>
            </div>
        )
    }
}
